package com.example.asyncwrite.service;

import com.alibaba.fastjson2.JSON;
import com.example.asyncwrite.mapper.OrderItemMapper;
import com.example.asyncwrite.mapper.OrderMapper;
import com.example.asyncwrite.model.Order;
import com.example.asyncwrite.model.OrderDTO;
import com.example.asyncwrite.model.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper itemMapper;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;


    public void createOrder() {
        for (long i = 0; i < 12; i++) {
            Order order = new Order(null, i + 10000, i + 20001, new BigDecimal(0), 1);
            List<OrderItem> list = new ArrayList<>();
            for (long j = 0; j < 3; j++) {
                OrderItem orderItem = new OrderItem(null, order.getOrderId(), order.getUserId(), order.getMerchantId(), new BigDecimal(2));
                list.add(orderItem);
            }
            for (OrderItem orderItem : list) {
                order.setAmount(order.getAmount().add(orderItem.getAmount()));
            }
            orderMapper.insert(order);
            for (OrderItem orderItem : list) {
                orderItem.setOrderId(order.getOrderId());
                itemMapper.insert(orderItem);
            }
            OrderDTO orderDTO = new OrderDTO();
            orderDTO.setOrder(order);
            orderDTO.setItems(list);
            kafkaTemplate.send("order_new", JSON.toJSONString(orderDTO));
        }

    }

    public List<OrderDTO> getOrderListByUserId(Long userId) {
        return orderMapper.getOrderListByUserId(userId);
    }

}
